package com.link.play.fit.ai.ui.main.fragment.control

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig.vipNeedPlanPay
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.CalControlData
import com.link.play.fit.ai.bean.CalControlReqData
import com.link.play.fit.ai.bean.ControlDayData
import com.link.play.fit.ai.bean.MealComponentsData
import com.link.play.fit.ai.bean.MealsData
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.bean.WorkoutData
import com.link.play.fit.ai.databinding.ControlListItemBinding
import com.link.play.fit.ai.databinding.ControlListItemLayoutBinding
import com.link.play.fit.ai.databinding.ControlResultAcLayoutBinding
import com.link.play.fit.ai.databinding.ControlResultReclistItemBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.store.CloudStore.uid
import com.link.play.fit.ai.ui.guide.WeightControlMethodFg
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.vip.VipFreeAc
import com.link.play.fit.ai.ui.weightcontrol.ac.WeighControlMethodAc
import com.link.play.fit.ai.utils.DateEx.getCurrentDayOfMonth
import com.link.play.fit.ai.utils.TimeUtils.calculateFinalTime
import com.link.play.fit.ai.utils.TimeUtils.completeControlDays
import com.link.play.fit.ai.utils.TimeUtils.convertTo24Hour
import com.link.play.fit.ai.utils.TimeUtils.getDateRange
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.UUID
import kotlin.math.abs

class ControlResutAc :
    BaseActivity<ControlResultAcLayoutBinding>(ControlResultAcLayoutBinding::inflate) {
    private var dateList: List<ControlDayData> = mutableListOf()

    companion object {
        var mCurrentSelectedPosition = -1
    }

    private var currentPage = 1
    private var currentPagePosition = 0
    private lateinit var pagedList: List<List<ControlDayData>>
    private var exerciseList: MutableList<WorkoutData> = mutableListOf()
    private var mealsList: MutableList<MutableList<MealsData>> = mutableListOf()
    private var currentMealsList: MutableList<MealsData> = mutableListOf()
    private var currentExerciseData: WorkoutData? = null

    private var dayNum = 0
    private var userGuide: UserGuide? = null
    private var calControlData: CalControlData? = null
    private var mPlanId = ""
    private var calControlReqData: CalControlReqData? = null
    private var texts: MutableList<String> = mutableListOf()
    private var isFirstContent = true
    private val foodListAdapter by lazy(LazyThreadSafetyMode.NONE) {
        FoodListAdapter()
    }
    private val exerciseListAdapter by lazy(LazyThreadSafetyMode.NONE) {
        ExerciseListAdapter()
    }
    val viewModel: ResultViewModel by lazy {
        ViewModelProvider(this)[ResultViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        EventBus.getDefault().register(this)
        obserLiveData()
        initData()
        initListener()
        binding.itemLayout.modifyPlanText.isVisible = false
        binding.itemLayout.neigouImg.isVisible = false
    }

    override fun useDefaultImmersive() {
        super.useDefaultImmersive()
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initData() = with(binding) {
        userGuide = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getSerializableExtra("user", UserGuide::class.java) ?: UserGuide()
        } else {
            @Suppress("DEPRECATION")
            (intent.getSerializableExtra("user") as UserGuide?) ?: UserGuide()
        }
        "userGuide  $userGuide".d()
        mPlanId = UUID.randomUUID().toString()
        userGuide?.let {
            it.haveWeighControlPlan = true
            it.planId = mPlanId
            CloudStore.set(
                DOC_USER_GUIDE, it
            )
        }

        userGuide?.let {
            dayNum = if(it.imperialMetric){
                (abs(it.goalWeightKg - it.weightKg) / it.perWeightKg * 7).toInt()
            }else{
                (abs(it.goalWeightLbs - it.weightLbs) / it.perWeightLbs * 7).toInt()
            }
            if (dayNum == 0) {
                dayNum = 30
            }

            calControlReqData = CalControlReqData().apply {
                userId = uid
                planId = mPlanId
                cycle = "1"
                height = it.heightCm.toString()
                gender = it.gender.toString()
                birth = "${it.bornYear}-${it.bornMonth}-${it.bornDay}"
                type = it.goal
                currentWeight = it.weightKg
                goalWeight = it.goalWeightKg
                weightLossGoal = abs(it.weightKg - it.goalWeightKg)
                weightLossCycle = dayNum.toString()
                customCalories = it.caloriesDaily.toString()
                customProtein = it.proteinDaily.toString()
                customCarbs = it.carbsDaily.toString()
                customFat = it.fatsDaily.toString()
            }


            "vipNeedPlanPay $vipNeedPlanPay isAppPurchaseVip ${it.isAppPurchaseVip}".d()
//            if (if(BuildConfig.DEBUG) false else vipNeedPlanPay) {
            if (vipNeedPlanPay) {
                if (it.isAppPurchaseVip) {
                    showData()
                } else {
                    resultLayout.isVisible = false
                    backImg.isVisible = false
                    zdLayout.root.isVisible = true
                }
            } else {
                if (isVip) {
                    showData()
                } else {
                    resultLayout.isVisible = false
                    backImg.isVisible = false
                    zdLayout.root.isVisible = true
                }
            }
        }
        texts.add(getString(R.string.the_waiting_time))
        texts.add(getString(R.string.the_long_loading))
        lifecycleScope.launch {
            while (true) {
                binding.itemLayout.theWaitingText.text = if (isFirstContent) texts[0] else texts[1]
                isFirstContent = !isFirstContent
                val delay = (3000 + (Math.random() * 2000)).toLong()
                delay(delay)
            }
        }
    }

    private fun initListener() = with(binding) {
        onBackPressedDispatcher.addCallback {
//            finish()
            goToAc(WeighControlMethodAc::class.java)
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right)
        }
        backImg.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        zdLayout.zdBackImage.isVisible = true
        zdLayout.zdBackImage.setOnClickListener {
            EventBus.getDefault().post("flushMain")
            finish()
        }
        startPlanText.setOnClickListener {
            lifecycleScope.launch {
                val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                user?.let {
                    userGuide?.isAppPurchaseVip = it.isAppPurchaseVip
                    userGuide?.planProductEndTime = it.planProductEndTime
                    userGuide?.subEndTime = it.subEndTime
                }
                userGuide?.let {
                    it.planStartTime = getCurrentDayOfMonth()
                    it.haveWeighControlPlan = true
                    it.planId = mPlanId
                    CloudStore.set(
                        DOC_USER_GUIDE, it
                    )
                }
                goToAc(MainAc::class.java) {
                    putExtra("controlType", "startPlan")
                    addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                }
                finish()
            }

        }
        zdLayout.homeImg.setOnClickListener {
            goToAc(MainAc::class.java) {
                putExtra("controlType", "backMain")
                addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
            finish()
        }
        zdLayout.startLayout.setOnClickListener {
//            if (if(BuildConfig.DEBUG) false else vipNeedPlanPay) {
            if (vipNeedPlanPay) {
                goToAc(ControlRefundAc::class.java) {
                    putExtra("buyType", "controlPlan")
                }
            } else {
                goToAc(VipFreeAc::class.java) {
                    putExtra("buyType", "controlPlan")
                }
            }
        }
        itemLayout.txImg.setOnClickListener {
            itemLayout.resetText.isVisible = !itemLayout.resetText.isVisible
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showData() = with(binding) {
        resultLayout.isVisible = true
        backImg.isVisible = true
        zdLayout.root.isVisible = false
        lifecycleScope.launch {
            val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            "isVip $isVip".d()
            user?.let {
                if (vipNeedPlanPay) {
                    if (it.isAppPurchaseVip) {
                        viewModel.getCalControl(calControlReqData!!)
                        it.planStartTime = getCurrentDayOfMonth()
                        CloudStore.set(
                            DOC_USER_GUIDE, it
                        )
                    }
                } else {
                    if (isVip) {
                        viewModel.getCalControl(calControlReqData!!)
                        it.planStartTime = getCurrentDayOfMonth()
                        CloudStore.set(
                            DOC_USER_GUIDE, it
                        )
                    }
                }
            }
        }
        userGuide?.let {
            "it.isAppPurchaseVip ${it.isAppPurchaseVip}".d()

            itemLayout.calValueText.text = it.caloriesDaily.toString()
            itemLayout.proteinValueText.text = it.proteinDaily.toString()
            itemLayout.fatValueText.text = it.fatsDaily.toString()
            itemLayout.carbsValueText.text = it.carbsDaily.toString()
            if (it.weighControlMethod == 0) { //断食
                binding.itemLayout.dayWeightText.text =
                    getString(R.string.day_weight_loss_plan, "$dayNum")
//                val lossWeightkg = abs(it.goalWeightKg - it.weightKg)
//                binding.itemLayout.lossGoalText.text =
//                    getString(R.string.weight_loss_goal, lossWeightkg.toString())
                if(it.imperialMetric){
                    val lossWeightkg = abs(it.goalWeightKg - it.weightKg)
                    binding.itemLayout.lossGoalText.text =
                        getString(R.string.weight_loss_goal, lossWeightkg.toString())
                }else{
                    val lossWeightLb = abs(it.goalWeightLbs - it.weightLbs)
                    binding.itemLayout.lossGoalText.text =
                        getString(R.string.weight_loss_goal_lbs, lossWeightLb.toString())
                }
                var fastStr = ""
                when (it.fastingGoal) {
                    0 -> {
                        binding.itemLayout.resetText.text =
                            getString(R.string.fasting_goal_text, "12+12")
                        fastStr = "+12"
                    }

                    1 -> {
                        binding.itemLayout.resetText.text =
                            getString(R.string.fasting_goal_text, "14+10")
                        fastStr = "+10"

                    }

                    2 -> {
                        binding.itemLayout.resetText.text =
                            getString(R.string.fasting_goal_text, "16+8")
                        fastStr = "+8"
                    }
                }
                val endTime = calculateFinalTime(it.fastingStartTime, fastStr)
                "endTime  $endTime".d()

                itemLayout.fastingText.text =
                    getString(
                        R.string.fasting_time,
                        "(${convertTo24Hour(it.fastingStartTime)}-${convertTo24Hour(endTime)})"
                    )

            } else {
                itemLayout.txImg.isVisible = false
                itemLayout.resetText.isVisible = false

                itemLayout.dayWeightText.text =
                    getString(R.string.day_weight_training_plan, "$dayNum")
                itemLayout.fastingText.text = getString(R.string.calorie_control)
                when (it.goal) { //0 gain ; 1 maintain ; 2 lose
                    0 -> {
//                        val weightkg = abs(it.goalWeightKg - it.weightKg)
//                        itemLayout.lossGoalText.text =
//                            getString(R.string.weight_gain_target_2, "$weightkg")
                        if(it.imperialMetric){
                            val weightkg = abs(it.goalWeightKg - it.weightKg)
                            binding.itemLayout.lossGoalText.text =
                                getString(R.string.weight_gain_target_2, "$weightkg")
                        }else{
                            val weightLbs = abs(it.goalWeightLbs - it.weightLbs)
                            binding.itemLayout.lossGoalText.text =
                                getString(R.string.weight_gain_target_2_lb, "$weightLbs")
                        }
                    }

                    1 -> {
                        itemLayout.lossGoalText.text = getString(R.string.keep_weight)
                    }

                    2 -> {
//                        val weightkg = abs(it.goalWeightKg - it.weightKg)
//                        itemLayout.lossGoalText.text =
//                            getString(R.string.weight_loss_goal, "$weightkg")
                        if(it.imperialMetric){
                            val weightkg = abs(it.goalWeightKg - it.weightKg)
                            binding.itemLayout.lossGoalText.text =
                                getString(R.string.weight_loss_goal, "$weightkg")
                        }else{
                            val weightLb = abs(it.goalWeightLbs - it.weightLbs)
                            binding.itemLayout.lossGoalText.text =
                                getString(R.string.weight_loss_goal_lb, "$weightLb")
                        }
                    }
                }
            }
        }
        dateList = completeControlDays(
            getDateRange(
                getCurrentDayOfMonth(),
                getCurrentDayOfMonth(),
                dayNum
            )
        )
        pagedList = dateList.chunked(7)
        mCurrentSelectedPosition = dateList.indexOfFirst { it.timeDay == getCurrentDayOfMonth() }
//        val (pageIndex, pagePosition) = calculateCyclePosition(getCurrentDayOfMonth(), endTime)

//        itemLayout.fgViewPager2.apply {
//            adapter = DayPagerAdapter(dateList, { position ->
//                "dateList  ${dateList[position].timeValue} ${dateList[position].timeDay}".d()
//            })
//            offscreenPageLimit = 2
//            setPageTransformer { page, position ->
//                page.translationX = position * page.width * 0.3f
//            }
//            currentItem = (dateList.size - 1) / 7 + 1
//        }

        setupRecyclerView()

        itemLayout.exercistList.setLayoutManager(LinearLayoutManager(this@ControlResutAc))
        itemLayout.exercistList.adapter = exerciseListAdapter

        itemLayout.foodList.setLayoutManager(LinearLayoutManager(this@ControlResutAc))
        itemLayout.foodList.adapter = foodListAdapter
    }

    private fun setupRecyclerView() {
        binding.itemLayout.recyclerView.apply {
            layoutManager = LinearLayoutManager(
                this@ControlResutAc,
                LinearLayoutManager.HORIZONTAL,
                false
            )
            adapter = PagerAdapter(pagedList, this@ControlResutAc) { globalPos, position ->
                handleItemSelection(globalPos)
                setData(1, position)
//                "dateList  ${dateList[globalPos].timeValue} ${dateList[globalPos].timeDay}".d()
            }
            // 添加分页吸附效果
            PagerSnapHelper().attachToRecyclerView(this)
        }
    }

    private fun handleItemSelection(globalPos: Int) {
        val prevSelected = mCurrentSelectedPosition
        mCurrentSelectedPosition = if (mCurrentSelectedPosition == globalPos) -1 else globalPos
        refreshAffectedItems(prevSelected, mCurrentSelectedPosition)
    }

    /**
     * 局部刷新新旧选中项
     */
    private fun refreshAffectedItems(oldPos: Int, newPos: Int) {
        listOf(oldPos, newPos).forEach { globalPos ->
            if (globalPos != -1) {
                val pageIndex = globalPos / 7 // 计算所在页
                val innerPos = globalPos % 7 // 计算页内位置
                // 局部刷新目标项
                (binding.itemLayout.recyclerView.findViewHolderForAdapterPosition(pageIndex)
                        as? PagerAdapter.PageViewHolder)?.let {
                    it.innerRecyclerView.adapter?.notifyItemChanged(innerPos)
                }
                binding.itemLayout.recyclerView.adapter?.notifyItemChanged(pageIndex)
            }
        }
    }

    private var retry: Int = 3
    private fun obserLiveData() {
        lifecycleScope.launch {
            viewModel.foodBeanLiveData.collect { bean ->
                "obserLiveData ${bean.msg}".d()
                if (bean.status == -1) return@collect
                if (bean.calControlData == null) {
                    if (retry > 0) {
                        retry -= 1
                        calControlReqData?.let {
                            viewModel.getCalControl(it)
                        }
                    }
                    "retry  $retry obserLiveData".d()
                }
                bean.let { data ->
                    "response bean  $data".d()

//                    calControlData = data.calControlData
//                    calControlData?.dailyPlans?.forEachIndexed { index, dailyPlans ->
//                        dailyPlans.workout?.let { exerciseList.add(it) }
//                        mealsList.add(dailyPlans.meals)
//                    }
                    calControlData = data.calControlData
                    exerciseList.clear()
                    mealsList.clear()
                    calControlData?.dailyPlans?.forEachIndexed { index, dailyPlans ->
                        dailyPlans.workout?.let { exerciseList.add(it) }
                        mealsList.add(dailyPlans.meals)
                    }
                    if (exerciseList.isNotEmpty() || mealsList.isNotEmpty()) {
                        showLayout()
                    }
                    "exerciseList ${exerciseList.size}  $exerciseList".d()
                    "mealsList ${mealsList.size}  $mealsList".d()
//                    if (exerciseList.isNotEmpty()) {
//                        currentExerciseData = exerciseList[0]
//                    }
//                    if (mealsList.isNotEmpty()) {
//                        currentMealsList = mealsList[0]
//                    }
//                    setData(currentExerciseData, currentMealsList)
                    setData(currentPage, currentPagePosition)

                }
            }
        }
    }

    private fun showLayout() = with(binding) {
        itemLayout.loadLayout.isVisible = false
        itemLayout.foodList.isVisible = true
        itemLayout.motionLayout.isVisible = true
        itemLayout.motionListLayout.isVisible = true
        startPlanText.isVisible = true
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setData(position: Int, index: Int) = with(binding) {
        "position $position  index $index currentPage $currentPage".d()

        "exerciseList $exerciseList  mealsList $mealsList".d()
        if (exerciseList.isEmpty() || mealsList.isEmpty()) return@with
        kotlin.runCatching {
            if (position == currentPage) {
                currentExerciseData = exerciseList[index]
                currentMealsList = mealsList[index]
                currentExerciseData?.let {
                    itemLayout.motionCalText.text = "${it.totalCaloriesBurned.toInt()}kcal"
                    itemLayout.exerciseText.text = it.exerciseType
                }
                "currentExerciseData $currentExerciseData".d()
                "currentMealsList $currentMealsList".d()
            } else {
                currentPage = position
                calControlReqData?.apply {
                    cycle = position.toString()
                }
                viewModel.getCalControl(calControlReqData!!)
            }
        }
        foodListAdapter.notifyDataSetChanged()
        exerciseListAdapter.notifyDataSetChanged()
    }
//    @SuppressLint("NotifyDataSetChanged")
//    private fun setData(workoutData: WorkoutData?, currentMealsList: MutableList<MealsData>) =
//        with(binding) {
//            workoutData?.let {
//                itemLayout.motionCalText.text = it.totalCaloriesBurned + "kcal"
//                itemLayout.exerciseText.text = it.exerciseType
//            }
////            var totCal = 0.0
////            currentMealsList.forEach {
////                totCal += it.mealTotalCalories.toDouble()
////            }
//
////        itemLayout.foodCalText.text = "${totCal}kcal"
//            foodListAdapter.notifyDataSetChanged()
//            exerciseListAdapter.notifyDataSetChanged()
//        }

    /**
     * 运动
     */
    inner class ExerciseListAdapter : RecyclerView.Adapter<ExerciseListAdapter.OneViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
            return OneViewHolder(
                layoutInflater.inflate(
                    R.layout.control_list_item,
                    parent,
                    false
                )
            )
        }

        @SuppressLint("NewApi")
        override fun onBindViewHolder(holder: OneViewHolder, position: Int) {
            val data = currentExerciseData?.exercises?.get(position)
            kotlin.runCatching {
                data?.let {
                    holder.itemBinding.nameText.text = "${it.exerciseName}${it.duration}"
                }

            }
        }

        override fun getItemCount(): Int {
            return currentExerciseData?.exercises?.size ?: 0
        }

        inner class OneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var itemBinding: ControlListItemBinding =
                ControlListItemBinding.bind(itemView)
        }
    }

    /**
     * 食物list
     */
    inner class FoodListAdapter : RecyclerView.Adapter<FoodListAdapter.OneViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
            return OneViewHolder(
                layoutInflater.inflate(
                    R.layout.control_result_reclist_item,
                    parent,
                    false
                )
            )
        }

        @SuppressLint("NewApi", "SetTextI18n")
        override fun onBindViewHolder(holder: OneViewHolder, position: Int) {

            holder.itemBinding.foodText.text = currentMealsList[position].mealName
            if (currentMealsList[position].mealTotalCalories.toDouble() > 0) {
                holder.itemBinding.foodCalText.isVisible = true
                holder.itemBinding.foodCalImg.isVisible = true
                holder.itemBinding.foodCalText.text =
                    "${currentMealsList[position].mealTotalCalories.toDouble().toInt()}kcal"
            } else {
                holder.itemBinding.foodCalText.isVisible = false
                holder.itemBinding.foodCalImg.isVisible = false
            }
//                    holder.itemBinding.foodCalText.text =
//                        "${currentMealsList[position].mealTotalCalories.toDouble().toInt()}" + "kcal"
            holder.itemBinding.list.setLayoutManager(LinearLayoutManager(this@ControlResutAc))
            holder.itemBinding.list.adapter =
                FoodListItemAdapter(currentMealsList[position].mealComponents)

        }

        override fun getItemCount(): Int {
            return currentMealsList.size
        }

        inner class OneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var itemBinding: ControlResultReclistItemBinding =
                ControlResultReclistItemBinding.bind(itemView)
        }
    }

    /**
     * 食物item
     */
    inner class FoodListItemAdapter(val data: List<MealComponentsData>) :
        RecyclerView.Adapter<FoodListItemAdapter.OneViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OneViewHolder {
            return OneViewHolder(
                layoutInflater.inflate(
                    R.layout.control_list_item,
                    parent,
                    false
                )
            )
        }

        @SuppressLint("NewApi")
        override fun onBindViewHolder(holder: OneViewHolder, position: Int) {
            kotlin.runCatching {
                holder.itemBinding.nameText.text =
                    data[position].mealComponentName + data[position].mealComponentDesc
            }
        }

        override fun getItemCount(): Int {
            return data.size
        }

        inner class OneViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            var itemBinding: ControlListItemBinding =
                ControlListItemBinding.bind(itemView)
        }
    }


    class PagerAdapter(
        private val pages: List<List<ControlDayData>>,
        private val context: Context,
        private val onItemClick: (Int, Int) -> Unit
    ) : RecyclerView.Adapter<PagerAdapter.PageViewHolder>() {

        inner class PageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val innerRecyclerView: RecyclerView = view.findViewById(R.id.pageRecyclerView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageViewHolder {
            return PageViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.control_item_page_container, parent, false)
            )
        }

        override fun onBindViewHolder(holder: PageViewHolder, pageIndex: Int) {
            holder.innerRecyclerView.apply {
                layoutManager = GridLayoutManager(context, 7) // 2列布局
                adapter = InnerAdapter(pages[pageIndex], pageIndex, context, onItemClick)
            }
        }

        override fun getItemCount() = pages.size
    }

    class InnerAdapter(
        private val items: List<ControlDayData>,
        private val pageIndex: Int,
        private val context: Context,
        private val onGlobalClick: (Int, Int) -> Unit
    ) : RecyclerView.Adapter<InnerAdapter.ItemViewHolder>() {
        var mPosition = -1

        inner class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            var itemBinding: ControlListItemLayoutBinding =
                ControlListItemLayoutBinding.bind(itemView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
            return ItemViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.control_list_item_layout, parent, false)
            )
        }

        override fun onBindViewHolder(holder: ItemViewHolder, innerPos: Int) {
            val globalPos = pageIndex * 7 + innerPos
            holder.itemBinding.itemNameText.text = items[innerPos].timeValue
            if (items[innerPos].isAfter) {
                holder.itemBinding.itemNameText.setTextColor(context.getColor(R.color.color_69))
            } else {
                holder.itemBinding.itemNameText.isSelected = (globalPos == mCurrentSelectedPosition)

            }
//            holder.itemView.apply {
//                isSelected = (globalPos == currentSelectedPosition)
//                setOnClickListener { onGlobalClick(globalPos) }
//            }
//            holder.itemBinding.itemNameText.isSelected =  (globalPos == currentSelectedPosition)

            holder.itemBinding.itemNameText.setOnClickListener {
                if (items[innerPos].isAfter) return@setOnClickListener
                if (globalPos == mCurrentSelectedPosition) return@setOnClickListener
                mPosition = innerPos
                onGlobalClick(globalPos, innerPos)
            }
        }

        override fun getItemCount() = items.size
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        if (event == "flushResult") {
            showData()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}